package org.jeecg.modules.achexamination.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.achexamination.entity.AchExamination;
import org.jeecg.modules.achexamination.service.IAchExaminationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.achexamination.vo.AchExaminationVo;
import org.jeecg.modules.common.api.ISysInfo;
import org.jeecg.modules.common.baseentity.BaseApiEntity;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ach_examination
 * @author: baochangrong
 * @Date: 2022-03-15
 * @Version: V1.0
 */
@Api(tags = "ach_examination")
@RestController
@RequestMapping("/achexamination/achExamination")
@Slf4j
public class AchExaminationController extends JeecgController<AchExamination, IAchExaminationService> {
    @Autowired
    private IAchExaminationService achExaminationService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISysInfo sysInfo;

    /**
     * 分页列表查询
     *
     * @param achExamination
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ach_examination-分页列表查询")
    @ApiOperation(value = "ach_examination-分页列表查询", notes = "ach_examination-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AchExamination achExamination,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {//组装vo以外的其他参数
        Map<String,String> queryParam = sysInfo.getMapQueryParamByReq(req);
        //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
        BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,achExamination,false); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo
        achExamination.setCreateBy(null);
        achExamination.setCreateTime(null);
        achExamination.setUpdateBy(null);
        achExamination.setUpdateTime(null);

        QueryWrapper<AchExamination> queryWrapper = QueryGenerator.initQueryWrapper(achExamination, req.getParameterMap());
        Page<AchExamination> page = new Page<AchExamination>(pageNo, pageSize);
        IPage<AchExamination> pageList = achExaminationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 获取所有考试数据 分页查询
     */
    @AutoLog(value = "getAchExaminationList-分页列表查询")
    @ApiOperation(value = "getAchExaminationList-分页列表查询", notes = "getAchExaminationList-分页列表查询")
    @GetMapping(value = "/getAchExaminationList")
    public Result<?> getAchExaminationList(AchExaminationVo achExaminationVo,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                           HttpServletRequest req) {
        Map<String,String> queryParam = sysInfo.getMapQueryParamByReq(req);
        //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
        BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,achExaminationVo,false); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo

        achExaminationVo.setCreateBy(null);
        achExaminationVo.setCreateTime(null);
        achExaminationVo.setUpdateBy(null);
        achExaminationVo.setUpdateTime(null);

        Page<AchExaminationVo> page = new Page<AchExaminationVo>(pageNo, pageSize);
        IPage<AchExaminationVo> pageList = achExaminationService.getAchExaminationList(page, achExaminationVo);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param achExamination
     * @return
     */
    @AutoLog(value = "ach_examination-添加")
    @ApiOperation(value = "ach_examination-添加", notes = "ach_examination-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AchExamination achExamination, HttpServletRequest req) {
        //获取当前登录用户信息
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        //		SysUser sysUser = sysUserService.getOneUser(username);// sysBaseAPI.getUserByName(username); 不能直接引用system模块，需使用APi调用
        LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户
        String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
        String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）,该编码随前端切换

        achExamination.setCreateBy(loginUser.getId());//当前用户
        achExamination.setDelFlag(0);//是否删除（0正常未删除，1已删除）
        achExamination.setIzOpen(1);//是否启用（0停用 1启用）
        achExamination.setSysOrgCode(sysOrgCode);//当前用户部门
        achExamination.setTenantId(tenantId);
        achExaminationService.save(achExamination);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param achExamination
     * @return
     */
    @AutoLog(value = "ach_examination-编辑")
    @ApiOperation(value = "ach_examination-编辑", notes = "ach_examination-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AchExamination achExamination) {
        achExaminationService.updateById(achExamination);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_examination-通过id删除")
    @ApiOperation(value = "ach_examination-通过id删除", notes = "ach_examination-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        achExaminationService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ach_examination-批量删除")
    @ApiOperation(value = "ach_examination-批量删除", notes = "ach_examination-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.achExaminationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_examination-通过id查询")
    @ApiOperation(value = "ach_examination-通过id查询", notes = "ach_examination-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AchExamination achExamination = achExaminationService.getById(id);
        if (achExamination == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(achExamination);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param achExamination
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AchExamination achExamination) {
        return super.exportXls(request, achExamination, AchExamination.class, "ach_examination");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AchExamination.class);
    }

    @GetMapping("/getExaminationPaperByExamId")
    public Result<?> getExaminationPaperByExamId(String examinationId) {
        return Result.OK(achExaminationService.getExaminationByExamId(examinationId));
    }

    /**
     * 复制考试相关的所有内容，考试、科目、计分规则、评分标准、试卷等
     *
     * @return
     */
    @PostMapping("/copyExamAll")
    public Result<?> copyExaminationAllThings(@RequestBody String params) {
        if (Objects.isNull(params) || params.length() < 10) {
            log.error("Params is Null");
            return Result.error("数据为空");
        }
        return achExaminationService.copyExamination(params) ? Result.OK("复制成功") : Result.error("复制失败");
    }

}
